package it.sandler.android.database;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * You can do what ever you want to do with SandlerDB.<br>
 * There are no restrictions. You can use SandlerDB for commercial use.<br>
 * <br>
 * Circle me on Google+: http://gplus.to/roberthahn<br>
 * SandlerDB on Google Code: http://code.google.com/p/sandler-db-for-android/<br>
 * <br>
 * Date: 04/16/2012
 * 
 * @author Robert Hahn
 * 
 */
public class SandlerTable extends SandlerBaseTable {

	private final Class<? extends SandlerEntity> entity;
	private final ArrayList<SandlerField> fields = new ArrayList<SandlerField>();
	private final ArrayList<SandlerRelationTable> relations = new ArrayList<SandlerRelationTable>();

	protected SandlerTable(Class<? extends SandlerEntity> entity) {
		this.entity = entity;

		for (Field f : entity.getDeclaredFields()) {
			if (SandlerField.isSandler(f)) {
				SandlerField sandlerField = new SandlerField(f);
				fields.add(sandlerField);
				if (sandlerField.hasRelation()) {
					relations.add(sandlerField.getRelation());
				}
			}
		}
	}

	/**
	 * Generates the Table Create Statement
	 * 
	 * @return
	 */
	@Override
	protected String create() {
		String c = "\"___id___\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ___dummy___ INTEGER, ";
		for (SandlerField f : fields) {
			if (f.getFieldName() != null && f.getFieldType() != null) {
				c += "\"" + f.getFieldName() + "\"" + " " + f.getFieldType()
						+ ", ";
			}
		}
		c = c.substring(0, c.length() - 2);
		return "CREATE TABLE " + getTableName() + " (" + c + ");";
	}

	/**
	 * Generates the Table DROP Statement
	 * 
	 * @return
	 */
	@Override
	protected String drop() {
		return "DROP TABLE IF EXISTS " + getTableName();
	}

	protected boolean hasRelation() {
		return relations.size() > 0;
	}

	protected ArrayList<SandlerRelationTable> getRelations() {
		return relations;
	}

	protected String getTableName() {
		return entity.getSimpleName();
	}
}
